<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Category;
use App\Model\Comments;
use App\Model\Content;
use App\Model\Like;
use App\Model\User;
use App\Server\JwtServer;

class DetailController extends Controller
{
  // 根据id获取详情信息
  public function getDetailById($id)
  {
    $content = Content::find($id);
    // 获取分类名称
    $catename = Category::find($content->cid)->name;
    // 获取评论
    $comments = Comments::where('cid', $id)->orderBy('id', 'desc')->get();
    // 获取点赞数量
    $zanCount = Like::where('cid', $id)->count();
    foreach ($comments as $v) {
      // 添加评论用户名
      $v->username = User::where('id', $v['uid'])->select('name')->first()->name;
    }
    return response()->json([
      'status' => 200,
      'msg' => '获取数据成功',
      'body' => [
        'id' => $content->id,
        'cid' => $content->cid,
        'catename' => $catename,
        'content' => $content,
        'comCount' => $comments->count(),
        'comment' => $comments,
        'zanCount' => $zanCount
      ]
    ]);
  }

  // 点赞
  public function addLike(Request $request, $id)
  {
    $token = $request->header('Token');
    $uid = JwtServer::decodeToken($token)->user_id;
    $res = Like::create([
      'uid' => $uid,
      'cid' => $id
    ]);
    if (!$res) return response()->json(['status' => 400, 'msg' => '点赞失败！']);
    return response()->json(['status' => 200, 'msg' => '点赞成功！']);
  }

  // 评论
  public function addComment(Request $request)
  {
    $id = $request->get('id');
    $content = $request->get('comment');
    // 根据token获取用户id
    $token = $request->header('Token');
    $uid = JwtServer::decodeToken($token)->user_id;
    $res = Comments::create([
      'cid' => $id,
      'uid' => $uid,
      'content' => $content
    ]);
    if (!$res) return response()->json(['status' => 400, 'msg' => '评论失败！']);
    return response()->json(['status' => 200, 'msg' => '评论成功！']);
  }
}
